<template>
  <scroll-dialog ref="dialogRef" :title="dialogTitle" :dialogVisible="isVisible" @clickSubmit="clickSubmit"
                 @close="close">
    <el-form ref="formRef" :model="form" label-width="100px">
      <XmFIntput quick v-model="form.expressSn" prop="expressSn" label="快递单号:" @blur="getExpressName(form.expressSn)">
      </XmFIntput>
      <XmFIntput quick :isDisabled="true" v-model="form.name" prop="name" label="快递名称:"></XmFIntput>
    </el-form>
  </scroll-dialog>
</template>
<script lang="ts" setup>
  import { ref, computed, watch } from 'vue'
  import ScrollDialog from '@/components/ScrollDialog/index.vue'
  import { editExpressInfo, getExpressAutonumber } from '@/api/modules/shop'
  import { usePromise } from '@/hooks/core/usePromise'
  import common from '@/utils/common'
  const props = defineProps({
    dialogVisible: {
      type: Boolean,
      default() {
        return false
      },
    },
    id: {
      type: Number,
      default() {
        return null
      },
    },
    orderData: {
      type: Object,
      default() {
        return {}
      },
    },
  })

  const emit = defineEmits(['update:dialogVisible', 'addSuccess'])
  const form = ref({
    name: '',
    expressSn: '',
    comCode: '',
    expressId: '',
    oldExpressSn: '',
  })
  const isVisible = ref(false)
  const dialogTitle = ref('订单发货')
  watch(
    () => props.dialogVisible,
    (val) => {
      isVisible.value = props.dialogVisible
      console.log('props.orderData =' + JSON.stringify(props.orderData))
      if (
        props.orderData.orderExpresses &&
        props.orderData.orderExpresses.length > 0
      ) {
        const { expressName, expressCode, expressSn, id, oldExpressSn } =
          props.orderData.orderExpresses[0]
        form.value.name = expressName
        form.value.expressSn = expressSn
        form.value.comCode = expressCode
        form.value.expressId = id
        form.value.oldExpressSn = expressSn
        dialogTitle.value = '修改物流'
      } else if (
        props.orderData.orderDetails &&
        props.orderData.orderDetails.length > 0
      ) {
        const { expressName, expressCode, expressSn, id, oldExpressSn } =
          props.orderData.orderDetails[0].simpleExpress
        form.value.name = expressName
        form.value.expressSn = expressSn
        form.value.name = expressName
        dialogTitle.value = '修改物流'
      }
    },
    { immediate: true }
  )

  watch(
    () => props.orderData,
    (val) => {
      // if (
      //   props.orderData.orderExpresses &&
      //   props.orderData.orderExpresses.length > 0
      // ) {
      //   const { expressName, expressCode, expressSn, id, oldExpressSn } =
      //     props.orderData.orderExpresses[0]
      //   form.value.name = expressName
      //   form.value.expressSn = expressSn
      //   form.value.comCode = expressCode
      //   form.value.expressId = id
      //   form.value.oldExpressSn = expressSn
      //   dialogTitle.value = '修改物流'
      // }
    },
    { immediate: true }
  )

  const formRef = ref()
  const isSubmit = ref(false)
  const { to } = usePromise()
  function clickSubmit() {
    const {
      comCode: expressCode,
      name: expressName,
      expressSn,
      expressId,
      oldExpressSn,
    } = form.value
    if (oldExpressSn === expressSn) {
      emit('update:dialogVisible', false)
      return
    }

    if (!expressCode) {
      isSubmit.value = true
      return
    }
    const { orderDetails } = props.orderData
    const detailIds = orderDetails.map((item: any) => {
      return item.id
    })
    formRef.value.validate(async (valid: Boolean) => {
      if (valid) {
        const { orderExpresses, id } = props.orderData
        // if (
        //   Array.isArray(orderExpresses) &&
        //   orderExpresses[0].expressSn === form.value.expressSn
        // ) {
        //   emit('update:dialogVisible', false)
        //   emit('addSuccess', true)
        //   return
        // }
        common.XmLoading(true)
        const [err, res] = await to(
          editExpressInfo({
            orderId: props.id || id,
            id: expressId ? expressId : null,
            expressCode,
            expressName,
            expressSn,
            detailIds,
          })
        )
        common.XmLoading()
        if (!err) {
          close()
          emit('addSuccess', true)
        }
      }
    })
  }

  function close() {
    emit('update:dialogVisible', false)
    form.value = {
      name: '',
      expressSn: '',
      comCode: '',
      expressId: '',
      oldExpressSn: '',
    }
  }

  function getExpressName(expressSn: string) {
    if (!expressSn) return
    common.XmLoading('正在校验快递数据')
    getExpressAutonumber({ expressSn })
      .then((res) => {
        common.XmLoading(false)
        const { comCode, name } = res.data
        form.value.comCode = comCode
        form.value.name = name
        
        if (isSubmit.value) {
          isSubmit.value = false
          clickSubmit()
        }
      })
      .catch(async () => {
        common.XmLoading(false)
        await common.syncAlert('识别快递错误，请重试')
        getExpressName(expressSn)
      })
  }
</script>
